﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Xml.Linq;

namespace Update.Servers.Standard {
    /// <summary>
    /// 标准服务器实现
    /// </summary>
    public class StandardServer : IUpdateServer
    {
        private string serverUrl;
        private bool enableChangelog;
        private string changelogFile = "changelog.txt";
        private WebClient webClient;
        
        public bool SupportsChangelog => enableChangelog;
        
        public StandardServer()
        {
            webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
        }
        
        public void Initialize(XElement config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));
                
            // 获取服务器URL
            serverUrl = config.Element("ServerUrl")?.Value;
            if (string.IsNullOrEmpty(serverUrl))
                throw new ArgumentException("未指定标准服务器URL");
                
            // 获取更新日志配置
            enableChangelog = bool.Parse(config.Element("EnableChangelog")?.Value ?? "false");
            string customChangelogFile = config.Element("ChangelogFile")?.Value;
            if (!string.IsNullOrEmpty(customChangelogFile))
                changelogFile = customChangelogFile;
        }
        
        public string GetServerVersion()
        {
            try
            {
                // 创建版本信息URL
                string versionUrl = $"{serverUrl.TrimEnd('/')}/version.txt";
                
                // 下载版本信息
                return webClient.DownloadString(versionUrl).Trim();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取服务器版本失败: {ex.Message}");
            }
        }
        
        public string DownloadUpdatePackage(string version, string savePath, Action<int,double, string> progressCallback)
        {
            try
            {
                // 确定更新包URL
                string updateUrl = $"{serverUrl.TrimEnd('/')}/update_{version}.zip";
                
                // 确定更新包保存路径
                string updatePackagePath = Path.Combine(savePath, $"update_{version}.zip");
                
                // 进度回调
                progressCallback?.Invoke(35, 0, $"正在从 {updateUrl} 下载更新包...");
                
                // 设置下载进度事件
                webClient.DownloadProgressChanged += (s, e) => {
                    progressCallback?.Invoke(35 + e.ProgressPercentage / 2, 0, $"下载更新包: {e.ProgressPercentage}%");
                };
                
                // 下载文件
                webClient.DownloadFile(new Uri(updateUrl), updatePackagePath);
                
                progressCallback?.Invoke(55, 0, "更新包下载完成");
                
                return updatePackagePath;
            }
            catch (Exception ex)
            {
                throw new Exception($"下载更新包失败: {ex.Message}");
            }
        }
        
        public string GetChangelog(string version)
        {
            if (!enableChangelog)
                return string.Empty;
                
            try
            {
                // 创建更新日志URL
                string changelogUrl = $"{serverUrl.TrimEnd('/')}/{changelogFile}";
                
                // 下载更新日志
                string changelog = webClient.DownloadString(changelogUrl);
                
                return changelog;
            }
            catch (Exception ex)
            {
                return $"获取更新日志失败: {ex.Message}";
            }
        }
        
        public void Dispose()
        {
            webClient?.Dispose();
        }
    }
} 